include(AddFileDependencies)
include(CMakeParseArguments)

function(pkd_replace_compiler_option var old new)
   # Replaces a compiler option or switch `old' in `var' by `new'.
   # If `old' is not in `var', appends `new' to `var'.
   # Example: pdk_replace_compiler_option(CMAKE_CXX_FLAGS_RELEASE "-O3" "-O2")
   # If the option already is on the variable, don't add it:
   if("${${var}}" MATCHES "(^| )${new}($| )")
      set(n "")
   else()
      set(n "${new}")
   endif()
   if("${${var}}" MATCHES "(^| )${old}($| )" )
      string(REGEX REPLACE "(^| )${old}($| )" " ${n} " ${var} "${${var}}")
   else()
      set(${var} "${${var}} ${n}")
   endif()
   set(${var} "${${var}}" PARENT_SCOPE)
endfunction()

function(pdk_add_header_files_for_glob headers_out glob)
   file(GLOB hds ${glob})
   set(${headers_out} ${hds} PARENT_SCOPE)
endfunction()

function(pdk_all_header_files headers_out additional_headerdirs)
   add_header_files_for_glob(hds *.h)
   list(APPEND all_headers ${hds})
   foreach(additional_dir ${additional_headerdirs})
      add_header_files_for_glob(hds "${additional_dir}/*.h")
      list(APPEND all_headers ${hds})
      add_header_files_for_glob(hds "${additional_dir}/*.inc")
      list(APPEND all_headers ${hds})
   endforeach()
   set(${hdrs_out} ${all_headers} PARENT_SCOPE)
endfunction()

function(pdk_process_sources out_var)
   cmake_parse_arguments(ARG "" "" "ADDITIONAL_HEADERS;ADDITIONAL_HEADER_DIRS" ${ARGN})
   set(sources ${ARG_UNPARSED_ARGUMENTS})
   if(MSVC_IDE OR XCODE)
      pdk_find_all_header_files(hdrs "${ARG_ADDITIONAL_HEADER_DIRS}")
      if (hdrs)
         set_source_files_properties(${hdrs} PROPERTIES HEADER_FILE_ONLY ON)
      endif()
      set_source_files_properties(${ARG_ADDITIONAL_HEADERS} PROPERTIES HEADER_FILE_ONLY ON)
      list(APPEND sources ${ARG_ADDITIONAL_HEADERS} ${hdrs})
   endif()
   if (APPLE)
      set(OBJCPP_FILES)
      foreach(objcpp_filename ${sources})
         get_filename_component(file_ext ${objcpp_filename} EXT)
         if ("${file_ext}" STREQUAL ".mm")
            list(APPEND OBJCPP_FILES ${objcpp_filename})
         endif()
      endforeach()
      if (OBJCPP_FILES)
         set_source_files_properties(${OBJCPP_FILES} PROPERTIES 
            COMPILE_FLAGS "-x objective-c++")
      endif()
   endif()
   set(${out_var} ${sources} PARENT_SCOPE)
endfunction()

function(pdk_find_all_header_files hdrs_out additional_headerdirs)
   pdk_add_header_files_for_glob(hds *.h)
   list(APPEND all_headers ${hds})
   foreach(additional_dir ${additional_headerdirs})
      pdk_add_header_files_for_glob(hds "${additional_dir}/*.h")
      list(APPEND all_headers ${hds})
      pdk_add_header_files_for_glob(hds "${additional_dir}/*.inc")
      list(APPEND all_headers ${hds})
   endforeach(additional_dir)
   set(${hdrs_out} ${all_headers} PARENT_SCOPE)
endfunction()



